#!/usr/bin/env python
# -*- coding: utf-8 -*-

#DEBUG
import cgitb;
cgitb.enable()
#END DEBUG
import os
import re
import sys
#import xml.dom.minidom as dom
sys.path.append('./lib')
sys.path.append('./lib/wsgiref')
from renyare.minidom import new_dom as dom # hacked minidom to support DOM2 namespace placing correctly
#import xml.dom.minidom as dom
from wsgiref.handlers import CGIHandler

import util
#import paths
from sqlalchemy import *

class forumData:
	NS = None
	def __init__(self, metadata, **args):
		"""
		Arguments:
			prefix - to give a prefix to the name in DB
			parent - a node in preant document to add xml code to
		"""
#prefix=None, rootNode=None):
		self.fName = (args.get('prefix') and self.name) or args['prefix']+self.name
		self.table = Table(self.fName, metadata)
		self.nsp = 'xf:'
		for i in self._table:
			self.table.append_column(i)
		self._xml(args.get('parent'))

	def _xml(self, rootNode):
		if(not rootNode):
			impl = dom.getDOMImplementation()
			outDoc = impl.createDocument(self.NS, self.name, None)
			self.xml = outDoc.documentElement
		else:
			self.xml = rootNode
		node = self.xml.ownerDocument.createElementNS(self.NS, self.fName)
		self.xml.appendChild(node)

	def _xForm(self, parent=None):
		xfNS='http://www.w3.org/TR/xforms'
		model = parent or self.xml.ownerDocument.createElementNS(xfNS, self.nsp+'instance')
		subm = self.xml.ownerDocument.createElementNS(None, self.nsp+'submission')
		subm.setAttribute('action', 'forum.py')
		subm.setAttribute('method', 'get')
		subm.setAttribute('id', 'f'+self.fName)
		model.appendChild(subm)
		for i in self.formdata.keys():
			#elem = self.xml.ownerDocument.createElementNS(self.NS, self.fName)
			elem = self.xml.ownerDocument.createElementNS(None, self.nsp+self.formdata[i][1])
			elem.setAttribute('ref', self.fName+self.formdata[i][0])
			label = self.xml.ownerDocument.createElementNS(None, self.nsp+'label')
			label.appendChild(self.xml.ownerDocument.createTextNode(self.formdata[i][2]))
			elem.appendChild(label)
			model.appendChild(elem)
		return model

	def _xhtmlForm(self, parent=None):
		"""
		Allowed XHTML form tags
		<button>
		<fieldset>
		<form>
		<input>
		<isindex>
		<keygen>
		<label>
		<legend>
		<optgroup>
		<option>
		<select>
		<textarea> 
		Allowed XHTML input types
		button
		checkbox
		file
		hidden
		image
		password
		radio
		reset
		submit
		text
		"""
		form = parent or self.xml.ownerDocument.createElementNS(None, 'form')
		form.setAttribute('action', 'forum.py')
		form.setAttribute('method', 'GET')
		for i in self.formdata.keys():
			elem = self.xml.ownerDocument.createElementNS(None, 'input')
			# To work on
			model.appendChild(elem)
		return model

class post(forumData):
	name = 'post'
	# Table structure
	_table = [ Column('id', Integer, primary_key=True, unique=True, autoincrement=True),
		Column('user_id', Integer, ForeignKey('user.id')),
		Column('text', String),
		Column('time',DateTime),
		Column('type', SmallInteger),
		Column('boxid', Integer) ]

	formdata = {
		'text':['text','input', 'Post text'], # name, type, label
		'username':['username','input', 'Username'], # name, type, label
		'submit':['submit','submit', 'OK'] # name, type, label
	}

class user(forumData):
	name = 'user'
	_table = [
		Column('id', Integer, primary_key=True, unique=True, autoincrement=True),
		Column('name', String),
		Column('grp_id',DateTime),
		Column('boxid', Integer)
	]
	formdata = {
		'name':['name','text', 'Username'] # name, type
	}


impl = dom.getDOMImplementation()
xml = impl.createDocument('test', 'page', None)
outDoc = xml
#pi = outDoc.createProcessingInstruction(u'xml-stylesheet', u'type="text/xsl" href="/xforms2xhtml.xsl"')
#xml.insertBefore(pi, xml.documentElement)
infoNode = outDoc.createElementNS(None, 'info')
outDoc.documentElement.appendChild(infoNode)
xfNS=u'http://www.w3.org/2002/xforms'
model = outDoc.createElementNS(xfNS, 'xf:instance')
outDoc.documentElement.appendChild(model)
data = ''

#print dir(sqa)
db = create_engine('sqlite:///forum.db')
#db.echo = True
metadata = BoundMetaData(db)
objects = [ post, user ]
obj = {}
prefix = ''
for i in range(0,len(objects)):
	t = objects[i](metadata, prefix=prefix)
	obj[t.table.fullname] = t
	aa = outDoc.importNode(t._xForm(model), deep=100)
	outDoc.documentElement.appendChild(aa)

#print "Content-type: text/xml\n"
print outDoc.toprettyxml()
sys.exit(0)
metadata.create_all()
i = obj['post'].table.insert()
i.execute({'text':'Some text 1', 'type':'0'}, {'text':'Some text 2', 'type':'0'} )
i = obj['post'].table.select()
res = i.execute()
data += 'DATA:'
d = res.fetchone()
while(d):
	data += str(d)
	d = res.fetchone()
data += '---'
res.close()
obj['post'].table.drop()
infoNode.appendChild(outDoc.createTextNode(data))
